package com.cn.remote;

import com.cn.file.AppendMessageResult;
import com.cn.file.MessageStore;
import com.cn.msg.Message;
import io.netty.channel.Channel;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ResponseFuture {

    private final int opaque;
    private final Channel processChannel;
    private final long timeoutMillis;
    private final long beginTimestamp = System.currentTimeMillis();
    private final CountDownLatch countDownLatch = new CountDownLatch(1);
    private volatile AppendMessageResult message;
    private volatile boolean sendRequestOK = true;


    /**
     * 等待服务端返回
     *
     * @param opaque         -- 进程标识
     * @param processChannel -- 正在进行的通道
     * @param timeoutMillis  -- 超时时间
     */
    public ResponseFuture(int opaque, Channel processChannel, long timeoutMillis) {
        this.opaque = opaque;
        this.processChannel = processChannel;
        this.timeoutMillis = timeoutMillis;
    }

    /**
     * 服务端返回请求后响应给调用端进程
     *
     * @param message
     */
    public void putResponse(AppendMessageResult message) {
        this.message = message;
        this.countDownLatch.countDown();
    }

    /**
     * 调用端等待超时
     *
     * @param timeout
     * @return
     * @throws InterruptedException
     */
    public AppendMessageResult waitResponse(long timeout) throws InterruptedException {
        this.countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
        return this.getMessage();
    }

    public boolean isSendRequestOK() {
        return sendRequestOK;
    }

    public void setSendRequestOK(boolean sendRequestOK) {
        this.sendRequestOK = sendRequestOK;
    }

    public AppendMessageResult getMessage() {
        return message;
    }

    public void setMessage(AppendMessageResult message) {
        this.message = message;
    }

    public long getBeginTimestamp() {
        return beginTimestamp;
    }
}
